<?php

namespace App\Http\Controllers\Admin;

use App\Models\Order;
use App\Models\SellOrder;
use App\Models\User;
use App\Models\UserAddress;
use Illuminate\Http\Request;

class UserController extends BaseController
{
    public function __construct()
    {
        parent::__construct();
        $this->middleware('check_admin_login');
    }

    public function randOne()
    {
        $user = User::query()->select(['id','wechat_nickname','wechat_avatar'])->where('user_type',0)->inRandomOrder()->first();

        $result = [
            'user_id'   => $user->id,
            'nickname'  => $user->wechat_nickname,
            'avatar'    => $user->wechat_avatar,
        ];
        return $this->ok($result);
    }

    public function index(Request $request)
    {
        $page                         = intval($request->get('page',1));
        $page                         = max($page ,1);
        $page_size                    = intval($request->get('page_size',10));
        $keyword                      = trim($request->get('keyword'));
        $start_time                   = strtotime(trim($request->get('start_time')));
        $end_time                     = strtotime(trim($request->get('end_time')));
        $type                         = intval($request->get('type'));  //0=全部 1=账户有余额 2=下过单的  3=黑名单 4买过书 5卖过书
        $order_by1                    = intval($request->get('order_by1'));  //1买书订单从高到低 2买书订单从低到高
        $order_by2                    = intval($request->get('order_by2'));  //1卖书订单从高到低 2卖书订单从低到高


        $builder = User::query()->where('user_type',1);

        if(!empty($keyword))
        {
            $like = '%'.$keyword.'%';
            $builder->where('wechat_nickname','like',$like);
        }

        if(!empty($start_time))
        {
            $builder->where('created_at','>=',$start_time);
        }

        if(!empty($end_time))
        {
            $builder->where('created_at','<=',$end_time);
        }

        switch ($type)
        {
            case 1:
                $builder->where('account','>',0);
                break;
            case 2:
                $builder->where('is_order',1);
                break;
            case 3:
                $builder->where('is_black',1);
                break;
            case 4:
                $builder->where('buy_orders_num','>',0);
                break;
            case 5:
                $builder->where('sell_orders_num','>',0);
                break;
        }

        switch ($order_by1)
        {
            case 1:
                $builder->orderBy('buy_orders_num','desc');
                break;
            case 2:
                $builder->orderBy('buy_orders_num','asc');
                break;
        }

        switch ($order_by2)
        {
            case 1:
                $builder->orderBy('sell_orders_num','desc');
                break;
            case 2:
                $builder->orderBy('sell_orders_num','asc');
                break;
        }

        $columns = ['id','wechat_avatar','wechat_nickname','created_at','account','buy_orders_num','sell_orders_num'];
        $list = $builder->orderBy('id','desc')->paginate($page_size,$columns,'page',$page);
        $items = [];
        if(!empty($list->items()))
        {
            foreach ($list->items() as $item)
            {
                //获取邀请好友总数
                $recommend_users_count = User::query()->where('recommend_user_id',$item->id)->count();

                $sell_orders_num = SellOrder::query()->where('state','>',2)->where('user_id',$item->id)->count();

                $items[] = [
                    'id'                    => $item->id,
                    'wechat_avatar'         => $item->wechat_avatar,
                    'wechat_nickname'       => $item->wechat_nickname,
                    'created_at'            => date('Y-m-d H:i:s',$item->created_at),
                    'account'               => $item->account,
                    'buy_orders_num'        => $item->buy_orders_num,
                    'sell_orders_num'       => $item->sell_orders_num,
                    //'sell_orders_num'       => $sell_orders_num,
                    'recommend_users_count' => $recommend_users_count,
                ];
            }
        }

        $data = [
            '_meta' => [
                'total_count'  => $list->total(),
                'page_count'   => $list->lastPage(),
                'current_page' => $list->currentPage(),
                'per_page'     => $list->perPage()
            ],
            "items" => $items
        ];

        return $this->res([
            'data' => $data
        ]);
    }

    public function show(Request $request)
    {
        $user_id = intval($request->get('id'));
        if(empty($user_id))
        {
            return $this->err(1,200,'','参数错误');
        }

        $user = User::find($user_id);
        if(empty($user))
        {
            return $this->err(1,200,'','用户不存在');
        }

        //判断是否关注公众号
        $is_official_account = 0;
        $wechat = \DB::table('wechat_users')->where('unionid',$user->unionid)->first();
        if(!empty($wechat))
        {
            $is_official_account = 1;
        }

        //买书订单数量
        $buy_orders_num = Order::query()->where('state','>',1)->where('user_id',$user->id)->count();

        //买了多少本书
        $orders = Order::query()->where('state','>',1)->where('user_id',$user->id)->get();
        $order_ids = collect($orders)->pluck('id');
        $buy_books_num =  \DB::table('order_items')->whereIn('order_id',$order_ids)->where('user_id',$user->id)->count();

        //退回订单数量
        $back_orders_num =  \DB::table('back_orders')->where('user_id',$user->id)->where('state','>',0)->count();

        $back_orders_list = \DB::table('back_orders')->where('user_id',$user->id)->where('state','>',0)->get();
        $back_orders_ids = [];
        if($back_orders_list->isNotEmpty())
        {
            foreach ($back_orders_list as $v)
            {
                $back_orders_ids[] = $v->id;
            }
        }
        //申请退回的书本数量
        $back_books_num = \DB::table('back_order_items')->whereIn('back_order_id',$back_orders_ids)->where('user_id',$user->id)->count();

        $sell_orders = SellOrder::query()->where('state','>',2)->where('user_id',$user->id)->get();
        $sell_order_ids = collect($sell_orders)->pluck('id');

        //$sell_orders_num = SellOrder::query()->where('user_id',$user->id)->where('state','>',2)->count();
        $sell_orders_num = count($sell_orders);  //卖书订单数量

        //dd($sell_order_ids);
        //卖了多少本书
        //$sell_books_num1 = \DB::table('sell_order_items')->whereIn('sell_order_id',$sell_order_ids)->where('user_id',$user->id)->where('state',1)->count();
        $sell_books_num1 = \DB::table('sell_order_items')->whereIn('sell_order_id',$sell_order_ids)->where('user_id',$user->id)->count();
        //未通过审核数量
        $sell_books_num2 = \DB::table('sell_order_items')->whereIn('sell_order_id',$sell_order_ids)->where('user_id',$user->id)->where('state',2)->count();

        $recommend_users_total = \DB::table('users')->where('recommend_user_id',$user->id)->count();
        $recommend_users_success = \DB::table('users')->where('recommend_user_id',$user->id)->where('is_recommend_coupon',1)->count();

        $addresses = UserAddress::query()->where('user_id',$user_id)->where('deleted',0)->orderBy('is_default','desc')->get();


        $account_records1 = [];
        $account_records2 = [];

        $list1 = \DB::table('sell_orders')->where('user_id',$user->id)->where('state',5)->get();
        if(!empty($list1))
        {
            foreach ($list1 as $v)
            {
                $books_num = \DB::table('sell_order_items')->where('sell_order_id',$v->id)->count();
                $account_records1[] = [
                    'actual_price'          => $v->actual_price,
                    'platform_success_time' => date('Y-m-d H:i:s',$v->platform_success_time),
                    'created_at'            => date('Y-m-d H:i:s',$v->created_at),
                    'books_num'             => $books_num,
                ];
            }
        }

        $get_money = \DB::table('user_account_records')->where('user_id',$user->id)->where('type',1)->where('is_get_money',1)->where('state',1)->sum('account');
        $list2 = \DB::table('user_account_records')->where('user_id',$user->id)->where('type',1)->where('is_get_money',1)->where('state',1)->get();
        if(!empty($list2))
        {
            foreach ($list2 as $v)
            {
                $account_records2[] = [
                    'remark'        => $v->remark,
                    'account'       => $v->account,
                    'created_at'    => $v->created_at,
                    'state'         => $v->state,
                ];
            }
        }
        $result = [
            'id'                        => $user->id,
            'is_black'                  => $user->is_black,
            'wechat_avatar'             => $user->wechat_avatar,
            'wechat_nickname'           => $user->wechat_nickname,
            'account'                   => $user->account,  //当前账户余额
            'created_at'                => date('Y-m-d H:i:s',$user->created_at),
            'is_official_account'       => $is_official_account,  //是否已关注公众号 1关注 0未关注
            'recommend_users_total'     => $recommend_users_total,  //邀请好友总数
            'recommend_users_success'   => $recommend_users_success,  //邀请的好友成功下单人数
            'buy_orders_num'            => $buy_orders_num,  //买书订单数量
            'buy_books_num'             => $buy_books_num,  //买了多少本书
            'sell_orders_num'           => $sell_orders_num,  //卖书订单数量
            'sell_books_num1'           => $sell_books_num1,  //卖了多少本书
            'sell_books_num2'           => $sell_books_num2,  //未通过审核数量
            'back_orders_num'           => $back_orders_num, //退回订单数量
            'back_books_num'            => $back_books_num,  //申请退回的书本数量
            'addresses'                 => $addresses,  //收货地址列表
            'account_records1'          => $account_records1, //余额收入明细
            'account_records2'          => $account_records2,  //余额提现明细
            'get_money'                 => $get_money, //已累计提现金额
        ];
        return $this->ok($result);
    }

    /**
     * 加入黑名单或取消黑名单
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function black(Request $request)
    {
        $user_id    = intval($request->get('user_id'));
        $is_black   = intval($request->get('is_black'));  //1加入黑名单 0取消黑名单
        if(empty($user_id))
        {
            return $this->err(1,200,'','参数错误');
        }

        $user = User::find($user_id);
        if(empty($user))
        {
            return $this->err(1,200,'','用户不存在');
        }

        if($is_black > 0)
        {
            $is_black = 1;
        }

        $data = [
            'is_black'      => $is_black,
            'updated_at'    => $this->time,
        ];
        $user->update($data);
        return $this->ok([]);
    }
}
